package com.lingjtx.common.core.util;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.HashMap;
import java.util.Map;

public class XmlHandle extends DefaultHandler {

    private String id;

    private Map<String, String> map;

    private StringBuffer content = new StringBuffer();

    private boolean tag = false;

    public Map<String, String> getMap() {
        return map;
    }

    @Override
    public void startDocument() throws SAXException {
        map = new HashMap<>();
    }

    @Override
    public void startElement(String s, String s1, String s2, Attributes attributes) throws SAXException {
        //通当前标签属性集合取属性值
        id = attributes.getValue("id");
        if (id != null) {
            tag = true;
        }
    }

    @Override
    public void endElement(String s, String s1, String s2) throws SAXException {
        if ("select".equals(s2)) {
            map.put(id, content.toString().replaceAll("\n", ""));
            content = new StringBuffer();
            tag = false;
        }
    }

    @Override
    public void characters(char[] chars, int i, int i1) throws SAXException {
        if (tag) {
            content.append(chars, i, i1);
        }
    }
}
